package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1. 获取日期
        List<LocalDate> dateList = getLocalDateList(begin,end);

        //获取每天营业额数据
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate orderTime : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(orderTime, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(orderTime, LocalTime.MAX);

            Map map = countByMap(beginTime,endTime,Orders.COMPLETED);

            Double amount = orderMapper.sumByMap(map);
            if (amount == null) {
                amount = 0.0;
            }
            turnoverList.add(amount);
        }
        //封装返回结果
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public UserReportVO getUserStatics(LocalDate begin, LocalDate end) {
        //1. 获取日期
        List<LocalDate> dateList = getLocalDateList(begin,end);

        //获取每天用户数据 用户总量：获取截至日期为当天结束时间的用户数， 新增：当天总量减去截止日期前一天总量
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = countByMap(null, endTime,null);
            totalUserList.add(userMapper.countByMap(map));
            map = countByMap(beginTime, endTime,null);
            newUserList.add(userMapper.countByMap(map));
        }

        //封装返回结果
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //获取日期
        List<LocalDate> dateList = getLocalDateList(begin,end);

        //获取每天订单数据 订单总量：获取截至日期为当天结束时间的用户数， 新增：当天总量减去截止日期前一天总量
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);

            Map map = countByMap(beginTime, endTime,null);
            orderCountList.add(orderMapper.countByMap(map));

            map = countByMap(beginTime,endTime, Orders.COMPLETED);
            validOrderCountList.add(orderMapper.countByMap(map));
        }
        //获取总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //获取有效订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //获取概率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0 ){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        //封装返回结果
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        //获取日期
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //获取数据
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime,endTime);

        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        //封装返回结果
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出最近30天运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 查询数据库获取最近30天营业数据： 营业额 订单完成率 新增用户 有效订单 平均客单价
        LocalDate end = LocalDate.now();
        LocalDate begin = end.minusDays(30);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);//查询概览数据
        //通过POI将数据写入excel文件
        //                              获取类对象    获取类加载器         用Stream流的方式从类路径下读取资源
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建新Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //填充数据
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充第二行
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + " 至 " + end);   // 填充时间段
            //填充第四行
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());    //填充营业额
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());     //填充完成率
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());    //填充新增用户数
            //填充第五行
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());    //填充有效订单数
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());    //填充平均客单价


            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //获取每天的数据
                BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(data.getTurnover());
                row.getCell(3).setCellValue(data.getValidOrderCount());
                row.getCell(4).setCellValue(data.getOrderCompletionRate());
                row.getCell(5).setCellValue(data.getUnitPrice());
                row.getCell(6).setCellValue(data.getNewUsers());
            }
            //将excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭流
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取日期列表
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getLocalDateList(LocalDate begin, LocalDate end) {
        //1. 获取日期
        List<LocalDate> dateList = new ArrayList<>(); //存放日期对象
        while (!begin.equals(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(begin);
        return dateList;
    }

    /**
     * 设置动态条件
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Map countByMap(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("end", endTime);
        map.put("begin",beginTime);
        map.put("status",status);
        return map;
    }
}
